import {
  Message
} from 'element-ui';

export function getSocket(uuid, callback, callbackErr) {
  return new Promise((resolve, reject) => {
    const socketUrl =
      window.api.socketUrl +
      JSON.parse(window.sessionStorage.getItem("userInfo")).user.userId +
      "?token=" +
      window.sessionStorage.getItem("token") +
      "&connectionId=" +
      uuid;

    let socket = new WebSocket(socketUrl);
    // 监听socket打开
    socket.onopen = function () {
      resolve(socket)
      console.log("浏览器WebSocket已打开");
    };
    let that = this;
    // 监听socket消息接收
    socket.onmessage = function (msg) {
      // 转换为json对象
      const data = JSON.parse(msg.data);
      switch (data.type) {
        case "HAND_SIGN_RETURN":
        case "CAMERA_SIGN_RETURN":
          if (data.message) {
            if (data.message.code === 'FAIL') {
              Message.error({
                message: data.message.message,
                customClass: 'war-message'
              })
              callbackErr(data.message)
              return
            }
            if (data.message.code === 'CANCEL') {
              Message.info({
                message: data.message.message,
                customClass: 'war-message'
              })
              callbackErr(data.message)
              return
            }
            callback(data.message)
          }
          break;
      }
    };
    // 监听socket错误
    socket.onerror = function () {
      reject()
      // that.$notify({
      //   title: "错误",
      //   message: "服务器异常，SOCKET已断开",
      //   type: "error",
      //   duration: 0,
      // });
    };
    // 监听socket关闭
    socket.onclose = function () {
      console.log("WebSocket已关闭");
    };
  })

}
